// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MessageCollectorAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Test.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Threading;
    using Microsoft.Robotics.Runtime;
    
    /// <summary>
    /// Consumer agent used to collect messages from the agent pipeline during testing.
    /// </summary>
    /// <typeparam name="T">The type of messages to collect.</typeparam>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
        "Microsoft.Design",
        "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
        Justification = "Agents clean up resources when OnDeactivated() is called.")]
    public class MessageCollectorAgent<T> : ConsumerAgent<T>
        where T : AgentMessage
    {
        /// <summary>
        /// The number of messages expected by this instance. Once this number is reached, the event is signaled
        /// </summary>
        private int currentMessageCount;

        /// <summary>
        /// The number of messages expected by this instance. Once this number is reached, the event is signaled
        /// </summary>
        private int expectedMessageCount;

        /// <summary>
        /// When signaled indicates that the desired number of messages was received.
        /// </summary>
        private AutoResetEvent resultsReadyEvent;

        /// <summary>
        /// Initializes a new instance of the MessageCollectorAgent class.
        /// </summary>
        /// <param name="producer">The name of the producer to subscribe to.</param>
        /// <param name="expectedMessageCount">The number of messages expected by this instance. Once this number is reached, the event is signaled</param>
        public MessageCollectorAgent(IProducer<T> producer, int expectedMessageCount = 1)
            : this(producer.Name + "_Collector", producer, expectedMessageCount)
        {
        }

        /// <summary>
        /// Initializes a new instance of the MessageCollectorAgent class.
        /// </summary>
        /// <param name="name">The name of the agent instance.</param>
        /// <param name="producer">The name of the producer to subscribe to.</param>
        /// <param name="expectedMessageCount">The number of messages expected by this instance. Once this number is reached, the event is signaled</param>
        public MessageCollectorAgent(string name, IProducer<T> producer, int expectedMessageCount = 1)
            : base(name, producer.Name)
        {
            this.expectedMessageCount = expectedMessageCount;
            this.Results = new Queue<T>();
            this.resultsReadyEvent = new AutoResetEvent(false);
        }

        /// <summary>
        /// Gets the collected results.
        /// </summary>
        public Queue<T> Results
        {
            get;
            private set;
        }

        /// <summary>
        /// Ensures that the completion event is reset whenever the agent is reactivated.
        /// </summary>
        public override void OnActivated()
        {
            this.resultsReadyEvent.Reset();
            base.OnActivated();
        }

        /// <summary>
        /// Reset the timer signal
        /// </summary>
        public void Reset()
        {
            this.resultsReadyEvent.Reset();
        }

        /// <summary>
        /// Waits until the number of expected messages is reached or until the timeout period lapsed
        /// </summary>
        /// <param name="timeout">The amount of time to wait before giving up, in ms</param>
        /// <returns>True if the expected count of messages was received before the timeout expired, false otherwise</returns>
        public bool Wait(int timeout)
        {
            return this.resultsReadyEvent.WaitOne(timeout);
        }

        /// <summary>
        /// Receives and stores the given message. 
        /// </summary>
        /// <param name="message">The message to enqueue</param>
        [ReceiverConfiguration(BlockIfFull = true)]
        public override void Receive(T message)
        {
            this.Results.Enqueue(message);
            this.currentMessageCount++;
            if (this.currentMessageCount == this.expectedMessageCount)
            {
                this.resultsReadyEvent.Set();
                this.currentMessageCount = 0;
            }
        }
    }
}
